package com.example.administrator.recorddemo20181101;

import android.Manifest;
import android.animation.Animator;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.recorddemo20181101.adapter.RecorderAdapter;
import com.example.administrator.recorddemo20181101.bean.FolderBean;
import com.example.administrator.recorddemo20181101.util.AnimUtil;
import com.example.administrator.recorddemo20181101.util.AppNetworkMgr;
import com.example.administrator.recorddemo20181101.util.AuditRecorderConfiguration;
import com.example.administrator.recorddemo20181101.util.CommomDialog;
import com.example.administrator.recorddemo20181101.util.CopyUtils;
import com.example.administrator.recorddemo20181101.util.DateUtil;
import com.example.administrator.recorddemo20181101.util.ExtAudioRecorder;
import com.example.administrator.recorddemo20181101.util.FailRecorder;
import com.example.administrator.recorddemo20181101.util.FileUtils;
import com.example.administrator.recorddemo20181101.util.MediaManager;
import com.example.administrator.recorddemo20181101.util.MtpUtils;
import com.example.administrator.recorddemo20181101.util.PopupWindowUtil;
import com.example.administrator.recorddemo20181101.util.ScreenUtil;
import com.example.administrator.recorddemo20181101.util.ZIPHeper;
import com.example.administrator.recorddemo20181101.view.AudioRecordButton;
import com.example.administrator.recorddemo20181101.view.RecordHintDialog;
import com.example.administrator.recorddemo20181101.view.RippleDiffuse;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import cn.andy.qpopuwindow.QPopuWindow;

public class MainActivity extends AppCompatActivity {

    private ListView mListView;
    private RippleDiffuse rippleDiffuse;
    private RecordHintDialog recordHintDialog;

    // 获取类的实例
    ExtAudioRecorder recorder;
    //录音地址
    String filePath = "";
    //dialog显示的图片
    private Drawable[] micImages;

    private int touchSlop;
    private TextView tv_spk;
    /**
     * 需要申请的运行时权限
     */
    private String[] permissions = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    /**
     * 被用户拒绝的权限列表
     */
    private List<String> mPermissionList = new ArrayList<>();
    private List<Recorder> mDates = new ArrayList<>();
    private RecorderAdapter mAdapter;
    private View animView;
    private String absolutePath = "";
    //发送QQ
    private TextView intent_file_image;
    private TextView intent_file_ok;
    private String edit;
    private int time = 0;
    private ImageView mIv_back;//返回
    private String list_Path = "";
    private String zipFile = "";
    private ImageView iv_top;//顶部
    private boolean scrollFlag = false;// 标记是否滑动
    private int lastVisibleItemPosition = 0;// 标记上次滑动位置
    private boolean isFalse = false;
    private File[] subFile;
    Recorder bean;
    private String record_dates;//录音的时间
    private int rawX;
    private int rawY;
    private String date;//复制文件之后创建的文件时间
    private String enterQQName;//发送QQ的文件名字

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        filePath = getIntent().getStringExtra("path");
        touchSlop = ViewConfiguration.get(MainActivity.this).getScaledTouchSlop();
        micImages = getRecordAnimPic(getResources());
        recordHintDialog = new RecordHintDialog(this, R.style.DialogStyle);

        AuditRecorderConfiguration configuration = new AuditRecorderConfiguration.Builder()
                .recorderListener(listener)
                .handler(handler)
                .uncompressed(true)//true不压缩
                .builder();
        recorder = new ExtAudioRecorder(configuration);
        initViews();
        initAdapter();
    }

    private void sortData(List<Recorder> mList) {
        Collections.sort(mList, new Comparator<Recorder>() {
            /**
             *
             * @param lhs
             * @param rhs
             * @return an integer < 0 if lhs is less than rhs, 0 if they are
             *         equal, and > 0 if lhs is greater than rhs,比较数据大小时,这里比的是时间
             */
            @Override
            public int compare(Recorder lhs, Recorder rhs) {
                Date date1 = DateUtil.stringToDate(lhs.getFileTime());
                Log.e("date1", lhs.getFileTime());
                Date date2 = DateUtil.stringToDate(rhs.getFileTime());
                Log.e("date2", rhs.getFileTime());
                // 对日期字段进行升序，如果欲降序可采用after方法
                if (date1.after(date2)) {
                    return 1;
                }
                return -1;
            }
        });
    }

    private void initAdapter() {
        getFileName(filePath);
        //删除 创建在ZIP 文件的文件
        boolean tmpZIP = fileIsExists(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + date);
        boolean tmpWAV = fileIsExists(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + enterQQName + ".wav");
        if (tmpZIP) {
            //有文件
            File file = new File(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + date);
            FileUtils.delFile(file, true);
            Log.e("压缩文件", "压缩文件");
        } else {
            //没有文件
            Log.e("没有压缩文件", "没有压缩文件");
        }
        if (tmpWAV) {
            File file = new File(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + enterQQName + ".wav");
            FileUtils.delFile(file, true);
            Log.e("WAV文件", "WAV文件");
        } else {
            Log.e("没有WAV文件", "没有WAV文件");
        }

        Log.e("filePath", filePath);
        mAdapter = new RecorderAdapter(this, mDates);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (animView != null) {
                    animView.setBackgroundResource(R.drawable.yinliang04);
                    animView = null;
                }
                //播放动画
                animView = view.findViewById(R.id.id_recorder_anim);
                animView.setBackgroundResource(R.drawable.play_anim);
                AnimationDrawable anim = (AnimationDrawable) animView.getBackground();
                anim.start();
                //播放音频
                Log.e("播放音频", filePath + mDates.get(position).filePath);
                MediaManager.playSound(filePath + mDates.get(position).filePath, new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        animView.setBackgroundResource(R.drawable.yinliang04);
                    }
                });
            }
        });
        //长按点击事件
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                QPopuWindow.getInstance(MainActivity.this).builder
                        .bindView(view, position)
                        .setPopupItemList(new String[]{"重命名", "删除", "发送"})
                        .setPointers(rawX, rawY)
                        .setOnPopuListItemClickListener(new QPopuWindow.OnPopuListItemClickListener() {
                            @Override
                            public void onPopuListItemClick(View anchorView, int anchorViewPosition, int position) {
                                switch (position) {//anchorViewPosition  条数
                                    case 0:
                                        showRename(anchorViewPosition);//重命名
                                        break;
                                    case 1:
                                        getDeleteDialog(anchorViewPosition);//删除
                                        break;
                                    case 2:
                                        File fileZIP = new File(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/");
                                        //判断文件夹是否存在，如果不存在就创建，否则不创建
                                        if (!fileZIP.exists()) {
                                            //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
                                            fileZIP.mkdirs();
                                        }
                                        if (AppNetworkMgr.isNetworkConnected(MainActivity.this)) {
                                            Log.e("连接", "连接");
                                            //发送
                                            Recorder recorder = mDates.get(anchorViewPosition);
                                            String enter_str = filePath + recorder.getFileName() + "_" + recorder.getFileTime() + ".wav";//旧文件
                                            enterQQName = recorder.getFileName();
                                            CopyUtils.copyFile(enter_str, Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + enterQQName + ".wav");
                                            Intent share = new Intent(Intent.ACTION_SEND);
                                            //创建组件
                                            ComponentName component = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
                                            share.setComponent(component);        //设置组件
                                            share.putExtra(Intent.EXTRA_STREAM, (FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + ".provider", new File(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + enterQQName + ".wav"))));
                                            share.setType("*/*");
                                            startActivity(Intent.createChooser(share, "分享到"));
                                        } else {
                                            Log.e("不连接", "不连接");
                                            Toast.makeText(MainActivity.this, "网络未连接", Toast.LENGTH_SHORT).show();
                                        }

                                        break;
                                }

                            }
                        }).show();

                return true;
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        rawX = (int) ev.getRawX();
        rawY = (int) ev.getRawY();
        return super.dispatchTouchEvent(ev);
    }

    public Vector<String> getFileName(String fileAbsolutePath) {
        Vector<String> vecFile = new Vector<>();
        File file = new File(fileAbsolutePath);
        subFile = file.listFiles();
        Log.e("手机路径", Environment.getExternalStorageDirectory().getParent());
        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            // 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                //获取文件夹路径
                list_Path = subFile[iFileLength].getAbsolutePath();
                Log.e("+++", list_Path);
                //获取文件名称
                String fileName = subFile[iFileLength].getName();
                //57c03565-dc1a-4950-bca5-621812973cda.wav
                Log.e("eee", "文件名 ： " + fileName);

                //文件名称
                int substring1 = fileName.lastIndexOf("_");
                Log.e("substring文件名称", substring1 + "");
                String substring2 = fileName.substring(substring1 + 1);
                //截取后面字符
                String str = substring2.substring(0, substring2.length() - 4);
                Log.e("str", str);
                //截取前面的字符到_
                String substring3 = fileName.substring(0, fileName.lastIndexOf("_"));
                Log.e("substring3", substring3);
                int mediaLength = Integer.parseInt(getMediaLength(list_Path));
                //毫秒转秒
                int i1 = mediaLength / 1000;
                int i = i1;
                bean = new Recorder(i, fileName, str);
                bean.setFileName(substring3);//文件名字
                bean.setFileTime(str);//排序的
                bean.setMediaLength(i);
                mDates.add(bean);
                sortData(mDates);
            }

        }
        return vecFile;
    }

    /**
     * 时长
     *
     * @param strMediaPath
     * @return
     */
    public String getMediaLength(String strMediaPath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(strMediaPath);
        String time = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        return time;
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        mDates.clear();
        initAdapter();
        Log.e("onRestart", "onRestart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MediaManager.pause();
        Log.e("onPause", "onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        MediaManager.resume();
        Log.e("onResume", "onResume");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaManager.release();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1001) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Log.e("", permissions[i] + " 权限被用户禁止！");
                }
            }
            AuditRecorderConfiguration configuration = new AuditRecorderConfiguration.Builder()
                    .recorderListener(listener)
                    .handler(handler)
                    .uncompressed(true)
                    .builder();
            recorder = new ExtAudioRecorder(configuration);
            initViews();
            initAdapter();
        }
    }

    private void checkPermissions() {
        // Marshmallow开始才用申请运行时权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) !=
                        PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (!mPermissionList.isEmpty()) {
                String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(this, permissions, 1001);
            }
        }
    }

    /**
     * 设置Dialog的图片
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            recordHintDialog.setImage(micImages[msg.what]);
        }
    };
    /**
     * 录音失败的提示
     */
    ExtAudioRecorder.RecorderListener listener = new ExtAudioRecorder.RecorderListener() {
        @Override
        public void recordFailed(FailRecorder failRecorder) {
            if (failRecorder.getType() == FailRecorder.FailType.NO_PERMISSION) {
                Toast.makeText(MainActivity.this, "录音失败，可能是没有给权限", Toast.LENGTH_SHORT).show();
                checkPermissions();
            } else {
                Toast.makeText(MainActivity.this, "发生了未知错误", Toast.LENGTH_SHORT).show();

            }
        }
    };

    /**
     * 滚动ListView到指定位置
     *
     * @param pos
     */
    private void setListViewPos(int pos) {
        if (android.os.Build.VERSION.SDK_INT >= 8) {
            //mListView.smoothScrollToPosition(pos);
            mListView.setSelection(pos);
        } else {
            mListView.setSelection(pos);
        }
    }


    private void initViews() {
        tv_spk = findViewById(R.id.tv_spk);
        rippleDiffuse = findViewById(R.id.rd);
        iv_top = findViewById(R.id.iv_top);
        iv_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setListViewPos(0);
            }
        });
        mListView = findViewById(R.id.id_listView);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
                        scrollFlag = false;
                        // 判断滚动到底部
                        if (mListView.getLastVisiblePosition() == (mListView
                                .getCount() - 1)) {
                            iv_top.setVisibility(View.VISIBLE);
                        }
                        // 判断滚动到顶部
                        if (mListView.getFirstVisiblePosition() == 0) {
                            iv_top.setVisibility(View.GONE);
                        }
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
                        scrollFlag = true;
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
                        scrollFlag = false;
                        break;
                }

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 当开始滑动且ListView底部的Y轴点超出屏幕最大范围时，显示或隐藏顶部按钮
                if (scrollFlag && ScreenUtil.getScreenViewBottomHeight(mListView) >= ScreenUtil
                        .getScreenHeight(MainActivity.this)) {
                    if (firstVisibleItem > lastVisibleItemPosition) {// 上滑
                        iv_top.setVisibility(View.VISIBLE);
                    } else if (firstVisibleItem < lastVisibleItemPosition) {// 下滑
                        iv_top.setVisibility(View.GONE);
                    } else {
                        return;
                    }
                    lastVisibleItemPosition = firstVisibleItem;
                }

            }
        });
        intent_file_ok = findViewById(R.id.intent_file_ok);
        intent_file_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppNetworkMgr.isNetworkConnected(MainActivity.this)) {
                    Log.e("连接", "连接");
                    enterQQ();
                } else {
                    Toast.makeText(MainActivity.this, "网络未连接", Toast.LENGTH_SHORT).show();
                }

            }
        });

        intent_file_image = findViewById(R.id.intent_file_image);
        //全选和反选
        intent_file_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//根目录
                if (isFalse) {
                    intent_file_image.setText("全选");
                    isFalse = true;
                    isFalse = false;
                    Log.e("全选", "全选");
                    mAdapter.setShowCheckbox(false);//不让显示
                    mAdapter.reverse();
                } else {
                    intent_file_image.setText("取消");
                    isFalse = false;
                    isFalse = true;
                    Log.e("取消", "取消");
                    mAdapter.setShowCheckbox(true);
                    mAdapter.all();
                }
            }
        });
        mIv_back = findViewById(R.id.iv_back);
        mIv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//返回
                finish();
            }
        });
        rippleDiffuse.setBtnOnTouchListener(new View.OnTouchListener() {
            float downY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downY = event.getY();
                        tv_spk.setText("松开  结束");
                        //检查sdcard
                        if (!isExitsSdcard()) {
                            String needSd = getResources().getString(R.string.Send_voice_need_sdcard_support);
                            Toast.makeText(MainActivity.this, needSd, Toast.LENGTH_SHORT).show();
                            return false;
                        }
                        File dir = new File(filePath);
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        /**
                         * 当前时间命名
                         */
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                        Date curDate = new Date(System.currentTimeMillis());
                        record_dates = formatter.format(curDate);
                        String filepath = record_dates + "_" + record_dates + ".wav";
                        File file = new File(dir, filepath);
                        absolutePath = file.getAbsolutePath();
                        Log.e("absolutePath", absolutePath);
                        // 设置输出文件
                        recorder.setOutputFile(absolutePath);
                        recorder.prepare();
                        recorder.start();

                        //弹出dialog
                        if (recorder.getState() != ExtAudioRecorder.State.ERROR) {
                            recordHintDialog.show();
                            recordHintDialog.moveUpToCancel();
                            return true;
                        }
                        return false;

                    case MotionEvent.ACTION_MOVE: {
                        if (recorder.getState() != ExtAudioRecorder.State.RECORDING) {
                            return false;
                        }
                        float offsetY = downY - event.getY();
                        if (offsetY > touchSlop) {
                            recordHintDialog.releaseToCancel();
                            tv_spk.setText("松开手指   取消发送");
                        } else {
                            recordHintDialog.moveUpToCancel();
                            tv_spk.setText("手指上滑   取消发送");
                        }
                        return true;
                    }

                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        recordHintDialog.dismiss();
                        if (recorder.getState() != ExtAudioRecorder.State.RECORDING) {
                            return false;
                        }
                        float offsetY = downY - event.getY();
                        if (offsetY > touchSlop) {
                            //删除录音
                            recorder.discardRecording();
                            tv_spk.setText("按住   说话");
                        } else {
                            //录音成功
                            time = recorder.stop();
                            if (time > 0.7) {//大于0.5秒 成功回调
                                Log.e("tiem", time + "");
                                tv_spk.setText("按住   说话");
                                //成功的处理
                                Toast.makeText(MainActivity.this, "录音成功", Toast.LENGTH_SHORT).show();
                                Recorder recorder = new Recorder(time, record_dates, record_dates);
                                mDates.add(recorder);
                                mDates.clear();
                                initAdapter();
                                mAdapter.notifyDataSetChanged();
                                mListView.setSelection(mAdapter.getCount() - 1);
                            } else {//反则  录音失败
                                String st2 = getResources().getString(R.string.The_recording_time_is_too_short);
                                Toast.makeText(MainActivity.this, st2, Toast.LENGTH_SHORT).show();
                                //如果 录音失败 那么删除这个文件，测试中，不删除这个文件，会叠加刷新出来这个文件，时长为0
                                File file1 = new File(absolutePath);
                                file1.delete();
                            }
                        }
                        recorder.reset();
                        return true;
                }
                return false;
            }
        });
    }

    /**
     * 发送多文件 ZIP
     */
    private void enterQQ() {
        File fileZIP = new File(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/");
        //判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!fileZIP.exists()) {
            //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
            fileZIP.mkdirs();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());
        date = formatter.format(curDate);
        //创建文件
        File filePate = new File(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + date + "/");
        //判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!filePate.exists()) {
            //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
            filePate.mkdirs();
        }
        List<Recorder> checkDatas = mAdapter.getCheckDatas();
        //判断集合 有没有条数

        if (checkDatas.size() > 0) {
            //选中之后返回的数据 进行遍历，获取到相对应的值
            for (int i = 0; i < checkDatas.size(); i++) {
                String filestr = checkDatas.get(i).getFilePath();
                Log.e("分享路径", filePath + filestr);
                //复制文件  赋值 checkDatas.get(i).getFileName()
                Log.e("checkDatas", checkDatas.get(i).getFileName());

                CopyUtils.copyFile(filePath + filestr, Environment.getExternalStorageDirectory().getPath() + "/果乐录音ZIP/" + date + "/" + checkDatas.get(i).getFileName() + ".wav");
            }
            File fileEnv = new File(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + date + "/");
            MtpUtils.scanMtpAsync(MainActivity.this, Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + date);

            File[] subQQFile = fileEnv.listFiles();
            //复制文件 循环
            final File[] fs = new File[subQQFile.length];
            for (int j = 0; j < subQQFile.length; j++) {
                String name = subQQFile[j].getPath();
                fs[j] = new File(name);
            }
            zipFile = date + ".zip";
            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        ZIPHeper.zipFiles(fs, Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + date + "/" + zipFile);

                        Intent share = new Intent(Intent.ACTION_SEND);
                        //创建组件，
                        ComponentName component = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
                        share.setComponent(component);        //设置组件
                        share.putExtra(Intent.EXTRA_STREAM, (FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + ".provider", new File(Environment.getExternalStorageDirectory() + "/果乐录音ZIP/" + date + "/" + zipFile))));
                        share.setType("*/*");
                        startActivity(Intent.createChooser(share, "分享到"));
                        Log.e("分享到", "分享到");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            th.start();

        } else {
            Toast.makeText(MainActivity.this, "未选择", Toast.LENGTH_SHORT).show();
        }

    }

    //判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * Sdcard是否存在
     */
    public static boolean isExitsSdcard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取录音时动画效果的图片
     */
    public static Drawable[] getRecordAnimPic(Resources res) {
        return new Drawable[]{res.getDrawable(R.drawable.v1),
                res.getDrawable(R.drawable.v2), res.getDrawable(R.drawable.v3),
                res.getDrawable(R.drawable.v4), res.getDrawable(R.drawable.v5),
                res.getDrawable(R.drawable.v6), res.getDrawable(R.drawable.v7), res.getDrawable(R.drawable.v6), res.getDrawable(R.drawable.v5), res.getDrawable(R.drawable.v4), res.getDrawable(R.drawable.v3), res.getDrawable(R.drawable.v2), res.getDrawable(R.drawable.v1)};
    }

    public class Recorder {
        private boolean checked;

        public boolean isChecked() {
            return checked;
        }

        public void setChecked(boolean checked) {
            this.checked = checked;
        }

        public Recorder(int recordLongtime, String fieName, String fileCreatTime) {
            this.time = recordLongtime;//时长
            this.filePath = fieName;//文件名 fiie。wav
            this.fileTime = fileCreatTime;
        }

        public float getTime() {
            return time;
        }

        public void setTime(float time) {
            this.time = time;
        }

        public String getFilePath() {
            return filePath;
        }

        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }

        float time;
        String filePath;//文件地址
        String fileName;//传入的文件名字
        String fileTime;//传入的系统时间

        public int getMediaLength() {
            return mediaLength;
        }

        public void setMediaLength(int mediaLength) {
            this.mediaLength = mediaLength;
        }

        int mediaLength;

        public String getFileShare() {
            return fileShare;
        }

        public void setFileShare(String fileShare) {
            this.fileShare = fileShare;
        }

        String fileShare;//传入发送

        public String getFileTime() {
            return fileTime;
        }

        public void setFileTime(String fileTime) {
            this.fileTime = fileTime;
        }


        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

    }


    private void getDeleteDialog(final int position) {
        new CommomDialog(MainActivity.this, R.style.dialog, "您确定删除此录音？", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    dialog.dismiss();
                    Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    //停止播放
                    MediaManager.release();
                    //删除录音
                    Log.e("删除录音", position + "-------" + "删除录音---");
                    Recorder recorder = mDates.get(position);
                    String enter_str = filePath + recorder.getFileName() + "_" + recorder.getFileTime() + ".wav";//旧文件
                    deleteFile(new File(enter_str));
                    mDates.remove(position);
                    mAdapter.notifyDataSetChanged();
                }
            }
        }).setTitle("提示").show();
    }

    private void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            //file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 重命名
     *
     * @param position
     */
    private void showRename(final int position) {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
        View view_Rename = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_rename, null);
        TextView cancel = view_Rename.findViewById(R.id.tv_rename_cancel);
        TextView sure = view_Rename.findViewById(R.id.tv_rename_ok);
        final EditText editText = view_Rename.findViewById(R.id.edit_text);
        final Dialog dialog = builder.create();
        dialog.show();
        dialog.getWindow().setContentView(view_Rename);
        //使ediText可以唤起软键盘
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                edit = editText.getText().toString();
                if (TextUtils.isEmpty(edit)) {
                    Toast.makeText(MainActivity.this, "请填写重命名", Toast.LENGTH_SHORT).show();
                    return;
                }
                /**
                 * 防止重命名冲突
                 */
                File file = new File(filePath);
                subFile = file.listFiles();
                for (int i = 0; i < subFile.length; i++) {
                    String path = subFile[i].getName();
                    Log.e("4444", path);
                    String substring3 = path.substring(0, path.lastIndexOf("_"));
                    if (substring3.equals(edit)) {
                        Toast.makeText(MainActivity.this, "重命名冲突", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                Recorder recorder = mDates.get(position);
                String a = filePath + recorder.getFileName() + "_" + recorder.getFileTime() + ".wav";//旧文件
                File oleFile = new File(a);
                recorder.setFileName(edit);
                String newFileName = filePath + edit + "_" + recorder.getFileTime() + ".wav";
                File newFile = new File(newFileName);
                // 执行重命名
                oleFile.renameTo(newFile);
                mDates.clear();
                initAdapter();
                mAdapter.notifyDataSetChanged();
            }
        });
    }
}
